from django.contrib.auth.models import AnonymousUser
from django.core.handlers.asgi import ASGIRequest
from django.utils.deprecation import MiddlewareMixin
from rest_framework.request import Request

from User.Auth import TokenAuth
from User.models import SiteUser

from django.http import HttpResponse


class TokenRefresh(MiddlewareMixin):

    def process_response(self, request: ASGIRequest, response, callback=None, callback_args=None, callback_kwargs=None):
        """
        所有响应返回给浏览器被调用 只能返回 HttpResponse
        """
        user: SiteUser = request.user
        try:
            if user.id is None:
                # print("无感刷新失效")
                return response  # 无用户不需要刷新
        except AttributeError as e:
            # 空值异常也是
            # print("无感刷新失效")
            return response

        user_id = user.id
        token = TokenAuth.make_user_token(user_id)

        # 将token添加到响应头
        if isinstance(response, HttpResponse):
            response['Authorization'] = f'{token}'
        else:
            response.headers['Authorization'] = f'{token}'

        return response
